package com.engine.modules.ytht.util;

import com.alibaba.fastjson.JSONObject;
import com.engine.common.util.RestTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

/**
 * @author FY
 * @version 1.0.0
 * @ClassName BusinessCode.java
 * @Description TODO
 * @createTime 2022年01月06日
 */
@Slf4j
@Component
public class BusinessCode {

    private static String Active;

    @Value("${spring.profiles.active}")
    public void setActive(String active) {
        BusinessCode.Active = active;
    }

    private static String HMAC_SHA256 = "HmacSHA256";

    public static String checkBusinessCode(String code) throws Exception {
        String result="";
        String urlbase="";
        String appkey = "TWkiRyQCNqpGTFkS3JISgnOCwezYHgHT"; //
        String appsecret = "o63lO3tUfUniy0eo1Cc3wcZcETrelsOC"; //
        log.info(BusinessCode.Active);
        System.out.println(code);
        switch (BusinessCode.Active) {
            case "dev":
            case "devl":
                urlbase = "https://yzstest.ynhtbank.com/dev/gateway";
                break;
            case "test":
                urlbase = "https://yzstest.ynhtbank.com/test/gateway";
                break;
            case "prod":
                urlbase = "https://yzstest.ynhtbank.com/gateway";
                break;
            case "devhuaye360":
                urlbase = "https://yzstest.huaye360.com/dev/gateway";
                break;
            case "testhuaye360":
                urlbase = "https://yzstest.huaye360.com/test/gateway";
                break;
            case "prohuaye360":
                appkey = "WZ0pN2vsMiCmgxil4LTqV9PRq5EKqnen";
                appsecret = "UA9baup6DxU6LTe5RjJ8qwbQaVRdYLAm";
                urlbase = "https://yzs.huaye360.com/gateway";
                break;
            default:
                break;
        }

        OkHttpClient httpClient = new OkHttpClient().newBuilder().build();

        //用全局标量中的账号信息，申请token，并保存
        RestTemplate restTemplate = new RestTemplate(RestTemplateUtil.GetHttpFactory());
        String urltoken = urlbase+"/oauth/token/?appkey=" + appkey + "&appsecret=" + appsecret;
//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED);
//        MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
//        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(map, headers);
        String body = restTemplate.getForObject(urltoken, String.class);
        String accessToken = JSONObject.parseObject(body).getJSONObject("data")
                .getString("accessToken");


        // 排序参数
        Map<String, String> signParams = new TreeMap<>();

        // 业务唯一请求
        String nonce = UUID.randomUUID().toString();// 业务请求唯一性
        String timestamp = String.valueOf(System.currentTimeMillis());
        signParams.put("nonce", nonce);
        signParams.put("timestamp", timestamp);// 5分钟内有效
        signParams.put("appkey", appkey);
        signParams.put("token", accessToken);
        signParams.put("secret", sign(accessToken + appsecret + nonce + timestamp, appsecret, HMAC_SHA256));

//		signParams.put("url参数", "url参数值");
        //以下是 get 请求才需要包含。下面只是例子 signParams.put("code", "烟农业务码")
        signParams.put("code", code);

        String signString = signString(signParams);
        String sign = sign(signString.toString(), appsecret, HMAC_SHA256);
        // 根据业务自行https请求
//		请求头包含以下信息

//        MediaType businessMediaType = MediaType.parse("application/json");
//		RequestBody smsBody = RequestBody.create(smsMediaType, "业务数据");
//        String url = urlbase+"/open/api/member/third/user?code=" + code;
        String urlcheckBusinessCode = urlbase+"/open/api/member/third/checkBusinessCode?code=" + code;
        Request requestcheckBusinessCode = new Request.Builder().url(urlcheckBusinessCode)// .method("POST", body)
                .addHeader("x-dv-timestamp", String.valueOf(timestamp)).addHeader("x-dv-appkey", appkey)
                .addHeader("x-dv-token", accessToken).addHeader("x-dv-nonce", nonce).addHeader("x-dv-sign", sign)
                .build();
        Response responsecheckBusinessCode = httpClient.newCall(requestcheckBusinessCode).execute();
        String rsBusinessCode = responsecheckBusinessCode.body().string();
        System.out.println(accessToken);
        System.out.println(rsBusinessCode);
        Integer codecheckBusinessCode = JSONObject.parseObject(rsBusinessCode).getInteger("code");
//        String datacheckBusinessCode = JSONObject.parseObject(rsBusinessCode).getString("data");
        if (codecheckBusinessCode == 0)
            result="true";

        //获取加密的身份证号码

//        body = restTemplate.getForObject(urltoken, String.class);
//        accessToken = JSONObject.parseObject(body).getJSONObject("data")
//                .getString("accessToken");
        // 排序参数
        signParams = new TreeMap<>();

        // 业务唯一请求
        nonce = UUID.randomUUID().toString();// 业务请求唯一性
        timestamp = String.valueOf(System.currentTimeMillis());
        signParams.put("nonce", nonce);
        signParams.put("timestamp", timestamp);// 5分钟内有效
        signParams.put("appkey", appkey);
        signParams.put("token", accessToken);
        signParams.put("secret", sign(accessToken + appsecret + nonce + timestamp, appsecret, HMAC_SHA256));

//		signParams.put("url参数", "url参数值");
        //以下是 get 请求才需要包含。下面只是例子 signParams.put("code", "烟农业务码")
        signParams.put("code", code);

        signString = signString(signParams);
        sign = sign(signString.toString(), appsecret, HMAC_SHA256);

//        MediaType businessMediaType = MediaType.parse("application/json");
//		RequestBody smsBody = RequestBody.create(smsMediaType, "业务数据");
        String urluser = urlbase+"/open/api/member/third/user?code=" + code;
//        String url = urlbase+"/open/api/member/third/checkBusinessCode?code=" + code;
        Request requestuser = new Request.Builder().url(urluser)// .method("POST", body)
                .addHeader("x-dv-timestamp", String.valueOf(timestamp)).addHeader("x-dv-appkey", appkey)
                .addHeader("x-dv-token", accessToken).addHeader("x-dv-nonce", nonce).addHeader("x-dv-sign", sign)
                .build();
        Response responseuser = httpClient.newCall(requestuser).execute();
        String rsuser = new String(responseuser.body().bytes(), StandardCharsets.UTF_8);
        System.out.println(accessToken);
        System.out.println(rsuser);
        Integer codeuser = JSONObject.parseObject(rsuser).getInteger("code");
        String datauser = JSONObject.parseObject(rsuser).getString("data");

//        codeuser=0;
//        String datauser = "zhFDPfWh14bdaq37JnxsCTBTeT4mK4fdDklVGhQwJMJYbe4qqG51hxLrxJeMt60y6VehXvIFAOspwgYymNPN5NX6p9uee8OhnuimmODRTji0Ovs20699biH52mX1ZRJa53co61l9wXjUgq+y7RTwBSoRXvwTou+YwNsK6CY2F0VwBbi2q6PNbnBZfVpkyah6iUle9SPCDBXv7YiZT/3ONw+zfrCzTy6S9tM3CkluRzI1X2JXHRxzMfJmhgeLAgAj+kHTJXWvc+6IT5n6KGJj5QUXl3knePdiZEQ2iMHc6rTkdBUCftSPgkfRgepaF4PxlVa+OXFkqZdt5UW5dDiSag==";
        if (codeuser == 0 && datauser!=null && datauser!=""){
            datauser=SuperAESUtil.decryptKeyIv(datauser,"4HX8Dq29nNQsvMFe","PiZH4TejWRf8ZlSV");
            System.out.println(datauser);
            result = JSONObject.parseObject(datauser).getString("identity");
        }

        return result;
    }

    public static String signString(Map<String, String> signParams) {
        StringBuilder signString = new StringBuilder();
        int i = 0;
        for (Map.Entry<String, String> param : signParams.entrySet()) {
            if (i == 0) {
                signString.append(param.getKey() + "=" + param.getValue());
            } else {
                signString.append("&" + param.getKey() + "=" + param.getValue());
            }
            i++;
        }
        return signString.toString();
    }

    public static String sign(String data, String key, String method) throws Exception {
        Mac mac = Mac.getInstance(method);
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), mac.getAlgorithm());
        mac.init(secretKeySpec);
        byte[] hash = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
        return DatatypeConverter.printHexBinary(hash).toLowerCase();
    }
}
